//
//  RentHouseDetailVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/19.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "RentHouseDetailVC.h"
#import "BaseTableViewCell.h"
#import "RenHouseBottomView.h"

#import "RenHouseDetailTopCell.h"
#import "RenHouseDetaMiddleCell.h"
#import "RenHouseDetaBottomCell.h"
#import "RenDetailSetionHeader.h"
#import "HouseDetailModel.h"
//#import "ImageBrowser.h"
@interface RentHouseDetailVC ()
/** <#note#> */
@property (nonatomic, weak) RenHouseBottomView *bottomView;

/** <#note#> */
@property (nonatomic, strong) HouseDetailModel *dataModel;

/** <#note#> */
@property (nonatomic, assign) CGFloat topViewH;

/** <#note#> */
@property (nonatomic, weak) UIButton *navBtn;
@end

@implementation RentHouseDetailVC



- (RenHouseBottomView *)bottomView{
    
    if (!_bottomView) {
        
        RenHouseBottomView *temp = (RenHouseBottomView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([RenHouseBottomView class]) owner:nil options:nil].firstObject;
        
        CGFloat bottomViewH = IPhoneX ? 83 : 49;
        
        temp.frame = CGRectMake(0, KScreenH - bottomViewH, KScreenW, bottomViewH);
        
        _bottomView = temp;
        
        _bottomView.myVC = self;
        
        [self.view addSubview:temp];
        
    }
    
    return _bottomView;
}
/**
 * 提交房源咨询
 *  house_id       *    房源id
 *  house_name     *    房源name
 *  content        *    咨询的内容
 *  user_tel       *    提问的手机号
 http://183.95.85.31:8001/index.php/api/House/addConsult

 */


- (void)onLineAskBtnDidTap:(NSString *)str{
    

    
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    NSLog(@"%@",self.houseId);
    parameters[@"house_id"] = self.houseId;
    parameters[@"house_name"] = self.dataModel.house_name;
    parameters[@"content"] = str;
    parameters[@"uid"] = myViewModel.user.uid;

    
    
//    parameters[@"id"] = self.houseId;

//    MJWeakSelf;
    [SVProgressHUD showWithStatus:@"正在提交..."];
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"House/addConsult" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            [SVProgressHUD showSuccessWithStatus:@"提交成功!"];
            
        } else {
            [SVProgressHUD showInfoWithStatus:error.domain];
        }
        
        
    }];
    
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"房源信息";
    
    self.topViewH = KScreenW / 16.0 * 9.0;

    
    self.groupTableView.tableFooterView = [[UIView alloc]init];
    self.groupTableView.backgroundColor = [UIColor whiteColor];
    
    self.groupTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.groupTableView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:[BaseTableViewCell identifierStr]];
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([RenHouseDetailTopCell class]) bundle:nil] forCellReuseIdentifier:[RenHouseDetailTopCell identifierStr]];
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([RenHouseDetaMiddleCell class]) bundle:nil] forCellReuseIdentifier:[RenHouseDetaMiddleCell identifierStr]];
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([RenHouseDetaBottomCell class]) bundle:nil] forCellReuseIdentifier:[RenHouseDetaBottomCell identifierStr]];
    
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([RenDetailSetionHeader class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[RenDetailSetionHeader identifierStr]];
    
    self.automaticallyAdjustsScrollViewInsets = NO;

    CGFloat tabbarH = IPhoneX ? 83 : 49;

    if (@available(iOS 11.0, *)) {

        self.groupTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
        self.groupTableView.contentInset = UIEdgeInsetsMake(0, 0, tabbarH, 0);
        
    }else{
        
        self.groupTableView.contentInset = UIEdgeInsetsMake(0, 0, tabbarH, 0);
        
    }
    
    self.bottomView.hidden = YES;
    
    
    
    MJWeakSelf
    self.groupTableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.groupTableView.mj_header beginRefreshing];
    
    
    [self setBack];
    
    
    
    
    
}

- (void)setBack{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [btn setImage:[UIImage imageNamed:@"lastBackNav"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"lastBackNav"] forState:UIControlStateHighlighted];
    
    [btn addTarget:self action:@selector(backTap) forControlEvents:UIControlEventTouchUpInside];

    
    btn.frame = CGRectMake(10, 0, 44, 44);
    
    btn.backgroundColor = [UIColor clearColor];
    
    btn.imageEdgeInsets = UIEdgeInsetsMake(8, 8, 8, 8);
    
    btn.hidden = YES;
    
    self.navBtn = btn;
    CGFloat tempH = IPhoneX ? 44 : 20;
    
    btn.top = tempH;
    
    [self.view addSubview:btn];
    
//
    
}

- (void)backTap{
    
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
}


- (void)loadData{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    NSLog(@"%@",self.houseId);
    parameters[@"id"] = self.houseId;
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"house/detail" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
                                                MYJSONSTR
            //
//                    [responseObject[@"data"]  propertyCode];
            
            
          weakSelf.dataModel =   [HouseDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
            
            
//            if (weakSelf.dataModel.house_pic.count > 0) {
//
//                [weakSelf downloadImage];
//
//            }else{
            
              
               weakSelf.navBtn.hidden = NO;

                weakSelf.bottomView.hidden = NO;
                
                weakSelf.bottomView.model = weakSelf.dataModel;
                
                [weakSelf.groupTableView.mj_header endRefreshing];
                
                [weakSelf.groupTableView reloadData];
//            }

            
            
        } else {
            
            [weakSelf.groupTableView.mj_header endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
    }];
    
    
    
}





- (void)downloadImage{
    
    dispatch_group_t group = dispatch_group_create();
    

    dispatch_group_enter(group);
    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:self.dataModel.house_pic.firstObject] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        NSLog(@"111111111");
        
        dispatch_group_leave(group);
        
    }];
    
    
    
    
    
    MJWeakSelf;
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        
        UIImage *image0 = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:weakSelf.dataModel.house_pic.firstObject];
        
        
        
        if (image0) {
            
            CGFloat imageViewH = KScreenW / image0.size.width * image0.size.height;
            // 重置放大缩小的比例
            weakSelf.topViewH = imageViewH;
            
            weakSelf.bottomView.hidden = NO;
            
            weakSelf.bottomView.model = weakSelf.dataModel;

            
            [weakSelf.groupTableView.mj_header endRefreshing];
            
            [weakSelf.groupTableView reloadData];
            
        } else {
            
            MJWeakSelf;
            [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:weakSelf.dataModel.house_pic.firstObject] options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                
                if (image) {
                    
                    CGFloat imageViewH2 = KScreenW / image.size.width * image.size.height;
                    // 重置放大缩小的比例
                    weakSelf.topViewH = imageViewH2;
                    
                    weakSelf.bottomView.hidden = NO;
                    
                    weakSelf.bottomView.model = weakSelf.dataModel;

                }else{
                    
                    weakSelf.topViewH = KScreenW / 16.0 * 9.0;
                    
                    weakSelf.bottomView.hidden = NO;
                    
                    weakSelf.bottomView.model = weakSelf.dataModel;

                }
                
                
                [weakSelf.groupTableView.mj_header endRefreshing];
                
                [weakSelf.groupTableView reloadData];
                
            }];
        }
        
  
        
      
        
        
    });
    
    
    
    
}





- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.dataModel == nil) {
        return 0;
    } else {
        return 3;
    }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.dataModel == nil) {
        return 0;
    } else {
        return 1;
    }
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section == 0) {

            RenHouseDetailTopCell *cell = [tableView dequeueReusableCellWithIdentifier:[RenHouseDetailTopCell identifierStr]];
        
            cell.imgH = self.topViewH;
            
            cell.model = self.dataModel;
        
            return cell;
            
        
    } else if (indexPath.section == 1){
        

        
        RenHouseDetaMiddleCell *cell = [tableView dequeueReusableCellWithIdentifier:[RenHouseDetaMiddleCell identifierStr]];

        cell.model = self.dataModel;
        return cell;
  
        
    }else{
        
        
        RenHouseDetaBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:[RenHouseDetaBottomCell identifierStr]];
        
        cell.model = self.dataModel;
        
        return cell;
        
        
    }
    
    
    
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return self.topViewH + 120;
    } else if (indexPath.section == 1) {
        return 149;
    }else{
        
        

        
        NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc]init];
        
        para.lineSpacing = 1;
        
        para.firstLineHeadIndent = 20;
        
        
        NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]init];
        tempDic[NSFontAttributeName] = MYFONT(15);
//        tempDic[NSParagraphStyleAttributeName] = para;
        tempDic[NSParagraphStyleAttributeName] = para;
        tempDic[NSKernAttributeName] = @(1.0f);

        
        CGSize size = [self.dataModel.house_details boundingRectWithSize:CGSizeMake(KScreenW - 24, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:tempDic context:nil].size;
        
        return size.height + 20;
        
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
 return 0.00001;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
   
    
    if (section == 0) {
        return 0.00001;
    } else {
        
        if (section == 1) {
            return 20;
        } else {
            return 36;
        }
        
    }
    
    
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        UIView *temp = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 0)];
        temp.backgroundColor = [UIColor whiteColor];
        return temp;
    } else if (section == 1) {
        UIView *temp = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 20)];
        temp.backgroundColor = viewBgGrey;
        return temp;
    }else{
        
        RenDetailSetionHeader *view = (RenDetailSetionHeader *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[RenDetailSetionHeader identifierStr]];
        
        view.frame = CGRectMake(0, 0, KScreenW, 36);
        
        return view;
        
    }
    

    

}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *temp = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 0)];
    temp.backgroundColor = [UIColor whiteColor];
    return temp;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
